define([], function() {
	return {
		title: ['<a href="user.html">个人中心</a>', "修改个人资料"],
		init: function(content) {
			let img = content.find("img");
			let imgFile = content.find(":file");
			let btns = content.find("button");
			img.on("error", function() {
				this.src = "img/_noimg.png";
			});

			btns.eq(0).on("click", function() {
				imgFile.trigger("click");
			});

			imgFile.on("change", function() {
				var f = imgFile[0].files[0];

				var reader = new FileReader();
				reader.onload = function() {
					let temp = new Image();
					temp.onload = function() {
						if(temp.width > 400 || temp.height > 400) {
							toastr.error("选择的图片高宽不能超过400像素");
						} else {
							img[0].src = temp.src;
						}
					}
					temp.src = reader.result;
				}
				reader.readAsDataURL(f);
			});

			btns.eq(1).on("click", function() {
				let formData = new FormData();
				formData.append("file",imgFile[0].files[0]);

				$.ajax({
					type: "post",
					url: "user/my-img.do",
					processData: false, // 不会将 data 参数序列化字符串
					contentType: false, // 根据表单 input 提交的数据使用其默认的 contentType
					data: formData,
					success: function(data) {
						if(data.ok) {
							toastr.success("修改头像成功");
						} else {
							toastr.error(data.message);
						}
					},
					dataType: "json"
				});

				return false;
			});

			$.get(
				"user/info.do",
				function(data) {
					img[0].src = data.userImg;
				}, "json"
			);

		}
	}
});